/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-17
 * Time: 18:15
 */
public class Solution {
    static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //处理边界问题
        if (list1 == null && list2 == null) {
            return null;
        }
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode newHead = null;
        ListNode cur = null;

        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
               if (newHead == null) {
                   newHead = list1;
                   cur = newHead;
                   list1 = list1.next;
               }else {
                   cur.next = list1;
                   cur = cur.next;
                   list1 = list1.next;
               }
            }else {
               if (newHead == null) {
                   newHead = list2;
                   cur = newHead;
                   list2 = list2.next;
               }else {
                   cur.next = list2;
                   cur = cur.next;
                   list2 = list2.next;
               }
            }
        }

        while (list1 != null) {
           cur.next = list1;
           cur = cur.next;
           list1 = list1.next;
        }

        while (list2 != null) {
            cur.next = list2;
            cur = cur.next;
            list2 = list2.next;
        }

        return newHead;
    }
}
